import requests
import json


class RequestClient(object):

    def __init__(self, login_url, username, password):
        self.username = username
        self.password = password
        self.login_url = login_url
        self.session = requests.Session()
        self.login()

    def login(self):
        self.session.post(self.login_url, params={"principal": self.username, "password": self.password})


class HarborApi(object):

    def __init__(self, harbor_domain, password, schema="https",
                 username="liuwei919"):
        self.schema = schema
        self.harbor_domain = harbor_domain
        self.harbor_url = self.schema + "://" + self.harbor_domain
        self.login_url = self.harbor_url + "/c/login"
        self.api_url = self.harbor_url + "/api"
        self.pro_url = self.api_url + "/projects"
        self.repos_url = self.api_url + "/repositories"
        self.username = username
        self.password = password
        self.client = RequestClient(self.login_url, self.username, self.password)

    # 获取项目列表
    def get_projects(self):
        """
        param: None
        return: [{project_name1: project_id1}, ...]
        """
        project_dic = json.loads(self.client.session.get(self.pro_url).content)
        return [{item["name"]: item["project_id"]} for item in project_dic]

    # 获取某库下的所有镜像
    def get_images(self, project_id):
        """
        param: project_id, 项目的id: 如 library 的id 20
        return: [{image_name1: image_id1}, ...]
        """
        img_dic  = json.loads(self.client.session.get(self.repos_url + "?project_id=" + str(project_id)).content)
        images = [{item["name"]: item["id"]} for item in img_dic]
        return images

    # 获取某镜像的下的labels列表
    def get_labels(self, img_name):
        """
        param: ima_name 分清镜像名: 如 labrary/javabase 才是完整镜像名
        return: 所有label列表, 降序, 默认把label全转成小写后排序
        """
        label_dic = json.loads(self.client.session.get(self.repos_url + "/%s/tags?detail=true" % img_name).content)
        labels = sorted([item["name"].lower() for item in label_dic], reverse=True)
        return labels

if __name__ == "__main__":
    harbor_domain = "bdp-registry.baonengmotor.com"
    password = "Harbor12345"
    res = HarborApi(harbor_domain, password, schema="http")
    print(res.get_images(14))
 